package com.imooc.reader.portal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.imooc.reader.portal.entity.Book;
import com.imooc.reader.portal.mapper.BookMapper;
import com.imooc.reader.portal.service.BookService;
import jakarta.annotation.Resource;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class BookServiceImpl implements BookService {
    @Resource
    private BookMapper bookMapper;

    @Override
    public IPage<Book> selectPage(Long categoryId, String order, Integer page, Integer rows) {
        IPage<Book> bookIPage = new Page<>(page, rows);
        QueryWrapper wrapper = new QueryWrapper<>();
        if (categoryId != null && categoryId != -1) {
            wrapper.eq("category_id", categoryId);
        }
        if (order != null) {
            if (order.equals("quantity")) {
                wrapper.orderByDesc("evaluation_quantity");
            } else if (order.equals("score")) {
                wrapper.orderByDesc("evaluation_score");
            }
        } else {
            // order为空时，默认按照热度排序
            wrapper.orderByDesc("evaluation_quantity");
        }
        bookIPage = bookMapper.selectPage(bookIPage, wrapper);
        return bookIPage;
    }

    @Cacheable(value = "book", key = "#bookId")
    @Override
    public Book selectById(Long bookId) {
        return bookMapper.selectById(bookId);
    }
}
